import type { ThemeService } from '../../../../types/constants'
import type { ThemeType } from '../../../../types/interfaces'
import { BlogThemeService } from '../../../../lib/abstract'
import { ToolKit } from '../../../../lib/utils/toolkit'
import { ConfigManager } from '../../../../module/config_manager'
import { AppModule } from '../../../../module/config_manager/types'
import { CustomElementStyleId, getPlatformValue, HEAD_THEME_VAR_NAME, HOSTNAME, logger } from '../../../../types/constants'
import { ThemeSourceMode } from '../../../../types/interfaces'
import { createThemeService } from '../custom_css/theme'

export class PageThemeService {
  // @Decorators.Identity
  private readonly name: string = 'PageThemeService'
  // @Decorators.PublicState
  static instance: PageThemeService
  // @Decorators.Dependency
  private readonly configManager = ConfigManager.getInstance()
  private themeService: ThemeService | null = null
  // @Decorators.Config
  readonly cssStyleId: string = CustomElementStyleId.ThemeCss

  static getInstance(): PageThemeService {
    if (!PageThemeService.instance) {
      PageThemeService.instance = new PageThemeService()
    }
    return PageThemeService.instance
  }

  init(): void {
    this.themeService = createThemeService(getPlatformValue(HOSTNAME))

    if (!this.themeService)
      logger.warn(`[${this.name}] 未找到对应平台的主题服务`)
  }

  /**
   * 注册主题样式
   */
  registerStyles(theme: ThemeType): void {
    if (theme === ToolKit.browser.theme.getCurrentTheme(ThemeSourceMode.INLINE)) {
      logger.debug(`[${this.name}] ${theme} 主题样式已生效，跳过启用`)
      return
    }

    if (!this.configManager.getFeatureEnabled(AppModule.ThemeStyle.id)) {
      logger.warn(`[${this.name}] 主题样式功能未开启，无法应用主题样式`)
      return
    }

    this.themeService?.registerThemeStyles(theme, `${this.cssStyleId}`)
    logger.info(`[${this.name}] 应用主题样式：${theme}`)
  }

  /**
   * 注销主题样式
   */
  unregisterStyles(): void {
    document.getElementById(this.cssStyleId)?.remove()
    document.documentElement.style.setProperty(HEAD_THEME_VAR_NAME, '')

    logger.info(`[${this.name}] 移除主题样式`)
  }

  /**
   * 应用文章标题样式
   */
  applyTitleStyles(value: string): void {
    if (!(this.themeService instanceof BlogThemeService))
      return

    if (value.length > 0) {
      // 应用文章标题样式
      this.themeService?.applySmartHeadingStyles(value as ThemeType)
      logger.info(`[${this.name}] 更新文章标题样式`)
    }
    else {
      // 恢复默认标题样式
      this.themeService?.restoreDefaultHeadingStyles()
      logger.info(`[${this.name}] 移除文章标题样式`)
    }
  }
}
